package com.example.orchid.paper.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.orchid.paper.PaperApplication;
import com.example.orchid.paper.R;
import com.example.orchid.paper.adapter.NewsAdapter;
import com.example.orchid.paper.entity.NewsListEntity.NewsEntity;
import com.example.orchid.paper.task.MyAsyncTask;

import java.util.ArrayList;

/**
 * 收藏夹，Activity
 * Created by Orchid on 2015-10-15.
 */
public class FavoriteActivity extends BaseActivity {
    private static final int REQUESTCODE_DETAIL = 8010;

    private ListView mListView;
    private NewsAdapter mAdapter = null;
    private ActionMode mActionMode;

    private ArrayList<NewsEntity> mNewsList = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_main);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(R.string.actionbar_title_fav);

        mInstance = this;

        mListView = (ListView) findViewById(R.id.list);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsEntity newsEntity = mNewsList != null ? mNewsList.get(position) : null;

                if (newsEntity == null) {
                    return;
                }

                if (mActionMode == null) {
                    Intent intent = new Intent();
                    intent.putExtra("id", newsEntity.id);
                    intent.putExtra("newsEntity", newsEntity);

                    intent.setClass(mInstance, NewsDetailActivity.class);
                    startActivityForResult(intent, REQUESTCODE_DETAIL);
                } else {
                    onListItemCheck(position);
                }
            }
        });

        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                onListItemCheck(position);
                return true;
            }
        });

        new LoadCacheNewsTask().executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
    }

    private void onListItemCheck(int position) {
        mAdapter.toggleSelection(position);
        boolean hasCheckedItems = mAdapter.getSelectedCount() > 0;

        if (hasCheckedItems && mActionMode == null) {
            mActionMode = startActionMode(new ActionModeCallback());
        } else if (!hasCheckedItems && mActionMode != null) {
            mActionMode.finish();
        }

        if (mActionMode != null) {
            mActionMode.setTitle(String.valueOf(mAdapter.getSelectedCount()) + " selected");
        }

    }

    private class ActionModeCallback implements ActionMode.Callback {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.getMenuInflater().inflate(R.menu.contextual_list_view, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

            ArrayList<NewsEntity> tempList = new ArrayList<>();
            tempList.addAll(mNewsList);

            SparseBooleanArray selected = mAdapter.getSelectedIds();
            for (int i = 0; i < selected.size(); i++) {
                if (selected.valueAt(i)) {
                    NewsEntity selectItem = (NewsEntity) mAdapter.getItem(selected.keyAt(i));
                    tempList.remove(selectItem);
                    PaperApplication.getNewsFavoriteDataSource().deleteFromFavorite(String.valueOf(selectItem.id));
                }
            }

            mNewsList = tempList;
            mAdapter.updateData(mNewsList);

            mode.finish();
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mAdapter.clearSelection();
            mActionMode = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.favorite, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_clear:
                PaperApplication.getNewsFavoriteDataSource().deleteFromFavorite();
                new LoadCacheNewsTask().executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
                return true;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        if (resultCode == REQUESTCODE_DETAIL) {
            new LoadCacheNewsTask().executeOnExecutor(MyAsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    private class LoadCacheNewsTask extends MyAsyncTask<String, Void, ArrayList<NewsEntity>> {
        @Override
        protected ArrayList<NewsEntity> doInBackground(String... params) {
            return PaperApplication.getNewsFavoriteDataSource().getFavoriteList();
        }

        @Override
        protected void onPostExecute(ArrayList<NewsEntity> newsEntities) {
            super.onPostExecute(newsEntities);

            if (newsEntities != null) {
                mNewsList = newsEntities;

                if (mAdapter == null) {
                    mAdapter = new NewsAdapter(mInstance, mNewsList);
                    mAdapter.setFavoriteFlag(true);
                    mListView.setAdapter(mAdapter);
                } else {
                    mAdapter.updateData(mNewsList);
                }
            }
        }
    }
}
